package code.example.javassist.property;

import code.example.javassist.maker.ClassMarker;

import java.util.concurrent.atomic.AtomicLong;

public class PropertyGetterMarkerImpl implements PropertyGetterMarker {
    AtomicLong atomicLong = new AtomicLong();
    @Override
    public PropertyGetter make(Object obj, String propertyName) throws Exception {
        String getterMethodString = getGetMethodString(obj,propertyName);
        String newClassName =  PropertyGetter.class.getName()+atomicLong.incrementAndGet();
        ClassMarker classMarker = new ClassMarker(newClassName);
        classMarker.addSuperClass(PropertyGetterImpl.class);
        classMarker.addInterface(PropertyGetter.class);
        classMarker.addMethod(getterMethodString);
        Class<PropertyGetter> classz = classMarker.make();
        return classz.newInstance();
    }

    private String getGetMethodString(Object obj, String propertyName){
        StringBuilder sb = new StringBuilder();
        String varName = obj.getClass().getSimpleName().toLowerCase();
        sb.append("    public Object get(Object bean, Object propertyName) {");
        sb.append(obj.getClass().getName())
                .append(" ")
                .append(varName)
                .append(" = ")
                .append("(")
                .append(obj.getClass().getName())
                .append(")")
                .append("bean;");
        sb.append(" return ")
                .append(varName)
                .append(".")
                .append("get")
                .append(Character.toUpperCase(propertyName.charAt(0)))
                .append(propertyName.substring(1))
                .append("();");
        sb.append("}");
        return sb.toString();
    }
}
